using Microsoft.EntityFrameworkCore;
using WeatherMcpServer.Data.Entities;

namespace WeatherMcpServer.Data.Repositories;

/// <summary>
/// EF Core 实现：预警规则仓储。
/// </summary>
public class EfWeatherRuleRepository : IWeatherRuleRepository
{
    private readonly WeatherDbContext _db;

    public EfWeatherRuleRepository(WeatherDbContext db)
    {
        _db = db;
    }

    public async Task<IReadOnlyList<WeatherRule>> GetEnabledRulesAsync(WeatherType? type = null, string? regionCode = null, CancellationToken ct = default)
    {
        var q = _db.WeatherRules.AsNoTracking().Where(r => r.IsEnabled);
        if (type.HasValue)
            q = q.Where(r => r.Type == type.Value);
        if (!string.IsNullOrWhiteSpace(regionCode))
            q = q.Where(r => r.RegionCode == regionCode);
        return await q.OrderBy(r => r.Id).ToListAsync(ct);
    }

    public async Task<WeatherRule> AddAsync(WeatherRule rule, CancellationToken ct = default)
    {
        await _db.WeatherRules.AddAsync(rule, ct);
        return rule;
    }

    public Task<int> SaveChangesAsync(CancellationToken ct = default) => _db.SaveChangesAsync(ct);
}
